package com.lexue.articlesync.service;

import com.lexue.articlesync.adapter.PlatformAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台适配器管理器
 */
@Slf4j
@Service
public class PlatformAdapterManager {
    
    private final Map<String, PlatformAdapter> adapters = new HashMap<>();
    
    /**
     * 自动注入所有平台适配器
     */
    @Autowired
    public PlatformAdapterManager(List<PlatformAdapter> adapterList) {
        for (PlatformAdapter adapter : adapterList) {
            adapters.put(adapter.getPlatformCode(), adapter);
            log.info("注册平台适配器: {} - {}", adapter.getPlatformCode(), adapter.getPlatformName());
        }
    }
    
    /**
     * 根据平台代码获取适配器
     */
    public PlatformAdapter getAdapter(String platformCode) {
        PlatformAdapter adapter = adapters.get(platformCode);
        if (adapter == null) {
            throw new IllegalArgumentException("不支持的平台: " + platformCode);
        }
        return adapter;
    }
    
    /**
     * 获取所有注册的适配器
     */
    public Map<String, PlatformAdapter> getAllAdapters() {
        return new HashMap<>(adapters);
    }
    
    /**
     * 检查平台是否支持
     */
    public boolean isSupported(String platformCode) {
        return adapters.containsKey(platformCode);
    }
    
    /**
     * 检查平台是否支持指定内容类型
     */
    public boolean supportContentType(String platformCode, String contentType) {
        PlatformAdapter adapter = adapters.get(platformCode);
        if (adapter == null) {
            return false;
        }
        
        String[] supportedTypes = adapter.getSupportedContentTypes();
        for (String type : supportedTypes) {
            if (type.equals(contentType)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取支持指定内容类型的所有平台
     */
    public Map<String, PlatformAdapter> getAdaptersByContentType(String contentType) {
        Map<String, PlatformAdapter> result = new HashMap<>();
        
        for (Map.Entry<String, PlatformAdapter> entry : adapters.entrySet()) {
            if (supportContentType(entry.getKey(), contentType)) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        
        return result;
    }
}